// base
import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image, ScrollView, Button, Form } from '@tarojs/components'
import { AtActionSheet, AtActivityIndicator } from 'taro-ui'
// redux
import { connect } from '@tarojs/redux'
import { DOREQUESTPERSONDETAIL, DOREQUESTPERSONALIKE } from './store/actions/pagepersondetail'
import { UPDATEPAGEPERSONDETAIL } from './store/types/pagepersondetail'
import { UPDATEIM } from '../../store/types/im'
// less
import './index.less'
// componnet
import NetworkError from '../../components/taro-ui/network-error'
// libs
import scaleImageSrc from '../../util/pagemethods/scaleImageSrc'
import { dealImgUrl, avater } from '../../configuration/staticimg'
import { showToast } from '../../crossplatform/apiservice/toast'
import EducationCard from '../../components/page-components/education-card/index'
import WorkExpCard from '../../components/page-components/work-exp-card/index'
import IntentionCard from '../../components/page-components/intention-card/index'
import If from '../../components/page-components/if'
import {
  insertArchiveRequest,
  removeArchiveRequest
} from '../../service/archive-operate-controller'
import { getTalentTalkTimeRequest } from '../../service/company-controller'
import { getMemberTalentTalkRequest } from '../../service/member-controller'
import Dialog from '../../components/page-components/dialog'
import { navigateTo } from '../../crossplatform/apiservice/navigate'
import pagejumplist from '../../configuration/pagejumplist.json'
import messagePush from '../../util/messagePush'
import IMController from '../../util/wy_im'
import { getGlobalData } from '../../configuration/globaldata'
import tool from '../../util/tool'

const mapActiontoProps = dispatch => ({
  updateState(payload) {
    dispatch({
      type: UPDATEPAGEPERSONDETAIL,
      payload: {
        ...payload
      }
    })
  },
  dorequest(payload) {
    return new Promise(resolve => {
      let promise = DOREQUESTPERSONDETAIL(payload)
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  },
  updateImState(payload) {
    dispatch({
      type: UPDATEIM,
      payload: {
        ...payload
      }
    })
  },
  getAlike(payload) {
    dispatch(DOREQUESTPERSONALIKE(payload))
  }
})

@connect(
  ({ pagepersondetail, userinfo, pageeducationinformation, im }) => ({
    ...pagepersondetail,
    openId: userinfo.openId,
    role: userinfo.role,
    companyId: userinfo.companyId,
    zhichuUserIdB: userinfo.zhichuUserIdB,
    isVip: userinfo.isVip,
    userId: userinfo.userId,
    degreeWrapList: pageeducationinformation.degreeWrap,
    ...im
  }),
  mapActiontoProps
)
class PersonDetail extends Component {
  config = {
    navigationBarTitleText: '个人详情'
  }

  state = {
    talkTime: 3,
    btnLoading: false,
    loadingData: false
  }

  componentWillMount() {
    // onLoad
    this.queryWrap()
  }

  componentDidMount() {
    // onready
  }

  componentDidShow() {
    // onshow
    const { role } = this.props
    if (role == 'company') {
      this.getTalkTime()
      // this.queryWrap()
    }
  }

  componentDidHide() {
    // onhide
    this.onCancel()
  }

  componentWillUnmount() {
    // onUnload
    this.onCancel()
  }

  queryWrap = () => {
    const params = this.$router && this.$router.params
    const {
      degreeWrapList,
      personDetail: { isOld, archiveId }
    } = this.props
    this.props
      .dorequest({
        userId: params && params.userId,
        degreeWrapList,
        isOld,
        archiveId
      })
      .then(({ archive_id, cmpUserId }) => {
        let userId = this.props.userId
        this.props.updateState({
          cmpUserId
        })
        this.getJobsAix({ userId, archiveId: archive_id })
        let timer = setTimeout(() => {
          clearTimeout(timer)
          this.createWyAccount()
        }, 100)
      })
  }

  getJobsAix = ({ userId, archiveId }) => {
    if (userId) {
      this.props.getAlike({ userId, archiveId })
    }
  }

  getTalkTime = () => {
    // 获取人才沟通次数
    const { companyId } = this.props
    getTalentTalkTimeRequest({ companyId }).then(({ data }) => {
      const { status, entry, message } = data
      if (status) {
        this.setState({
          talkTime: entry
        })
      } else {
        showToast({
          title: message || '获取次数失败'
        })
      }
    })
  }

  onReload = () => {
    this.queryWrap()
  }

  delay(time = 0) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve()
      }, time)
    })
  }

  onShareAppMessage() {
    const params = this.$router && this.$router.params
    return {
      title: '这有一个人才，发给你看看～',
      path: `/pages/person-detail/index?userId=${params.userId}`,
      imageUrl: scaleImageSrc(this.props.personDetail.userAvator)
    }
  }
  favoritebtnClick = tool.throttle(() => {
    const { collected } = this.props
    if (collected) {
      this.onEscPost()
    } else {
      this.onInsertPost()
    }
  })
  onInsertPost = () => {
    const {
      personDetail: { id: archiveId },
      userId
    } = this.props
    insertArchiveRequest({ archiveId, userId }).then(({ data }) => {
      if (data && data.entry) {
        this.queryWrap()
      } else {
        showToast({
          title: '收藏失败！'
        })
      }
    })
  }

  onEscPost = () => {
    const {
      personDetail: { id: archiveId }
    } = this.props
    removeArchiveRequest({ archiveIds: [archiveId] }).then(({ data }) => {
      if (data.status) {
        this.queryWrap()
      } else {
        showToast({
          title: '取消失败！'
        })
      }
    })
  }

  callTo = tool.throttle(() => {
    const { loadingData } = this.state
    if (!loadingData) {
      const { role, companyId, zhichuUserIdB, isVip, userId, cmpUserId } = this.props
      this.setState({
        btnLoading: true
      })
      if (role == 'company' && companyId && zhichuUserIdB) {
        if (isVip) {
          this.goChat()
          getMemberTalentTalkRequest({
            companyId,
            userId,
            cmpUserId,
            type: 'B'
          }).then(({ data }) => {
            const { entry, status, message } = data
            if (status) {
              this.onCancel()
            } else {
              showToast({
                title: message || '已经沟通3次，无法沟通'
              })
              this.setState({
                btnLoading: false
              })
            }
          })
        } else {
          this.props.updateState({
            modalReadyVisible: true
          })
          this.setState({
            btnLoading: false
          })
        }
      } else {
        showToast({
          title: '仅支持企业用户拨打'
        })
        this.setState({
          btnLoading: false
        })
      }
    } else {
      console.log('数据正在加载')
    }
  })

  gotoVipRecharge = () => {
    // 跳转会员充值页面
    this.onCancel()
    navigateTo({
      url: `${pagejumplist['vip-recharge'].path}`
    })
  }

  onConnect = tool.throttle(() => {
    const { loadingData } = this.state
    if (!loadingData) {
      const { talkTime } = this.state
      this.setState({
        btnLoading: true
      })
      if (talkTime > 0) {
        this.goChat()
        // 还有沟通次数
        const { companyId, userId, mobile, cmpUserId } = this.props
        getMemberTalentTalkRequest({
          companyId,
          userId,
          cmpUserId,
          type: 'B'
        }).then(({ data }) => {
          const { entry, status, message } = data
          if (status) {
            this.onCancel()
          } else {
            showToast({
              title: message || '已经沟通3次，无法沟通'
            })
            this.setState({
              btnLoading: false
            })
          }
        })
      } else {
        showToast({
          title: '已经沟通3次，无法沟通'
        })
        this.onCancel()
        this.setState({
          btnLoading: false
        })
      }
    } else {
      console.log('数据正在加载')
    }
  })

  goChat = () => {
    let timer = setTimeout(() => {
      clearTimeout(timer)
      this.setState({
        btnLoading: false,
        loadingData: false
      })
    }, 500)
    this.props.updateImState({
      msgArray: []
    })
    navigateTo({
      url: `${pagejumplist['chat-page'].path}`
    })
  }

  createWyAccount = () => {
    this.setState({
      loadingData: true
    })
    const imId = getGlobalData('IM_ID')
    const {
      userInfo: { userId, avatarUrl, name, userName, birth = '', gender, extra, mobile, extra3, id }
    } = this.props
    let identifier = (!!extra3 ? id : userId) + 'c' + imId 
    // 处理老数据
    !!extra3 ? (identifier = identifier + 'old') : null
    let userInfo = {
      userName: name || userName,
      userAvator: scaleImageSrc(avatarUrl),
      userId: !!extra3 ? id : userId,
      sex: gender || extra,
      gmtBirth: birth,
      mobile: mobile,
      isOld: !!extra3
    }
    IMController.createAccount({
      userId: identifier,
      role: 'personal',
      userInfo
    }).then(() => {
      console.log(this.props.selToID, 'toididid')
      this.setState({
        loadingData: false
      })
    })
  }

  onCancel = () => {
    this.props.updateState({
      modalVisible: false,
      modalReadyVisible: false
    })
  }

  openPic = e => {
    const { elegantDemeanour = [] } = this.props
    const current = e.currentTarget.dataset.url
    Taro.previewImage({
      current: dealImgUrl(current), // 当前显示图片的http链接
      urls: elegantDemeanour.map(f => dealImgUrl(f.pic)) // 需要预览的图片http链接列表
    })
  }

  formSubmit = e => {
    let { formId } = e.detail
    const { openId, userId } = this.props
    messagePush.insertFormId({ userId, formId, openId })
  }

  render() {
    const {
      userInfo,
      personDetail,
      wantWork = [],
      educationInformation = [],
      workExp = [],
      elegantDemeanour = [],
      collected,
      modalVisible,
      modalReadyVisible
    } = this.props
    const { isOld } = personDetail
    const { talkTime, btnLoading } = this.state
    return (
      <View className="PersonDetail_id51121">
        <NetworkError visible={this.props.networkerror} onReload={this.onReload} />
        <View className={`PersonDetail_id51121Wrap ${this.props.networkerror ? 'hide' : ''}`}>
          <View className="btns-wrap">
            <View className="btn-bg">
              <Button OpenType="share" className="share-btn" />
              <Image
                className="share-img"
                src="https://imagesize.hrwork.com/sp/files/5fbe70d4-90ca-487d-9b4f-98d1e2099484.png"
              />
            </View>
            <If visible={!isOld}>
              <View
                className={`btn-bg ${collected ? 'btn-bg-active' : ''}`}
                onClick={this.favoritebtnClick}
              >
                <Image
                  className="favorite-img"
                  src={
                    collected
                      ? 'https://imagesize.hrwork.com/sp/files/1a28894c-7f27-41de-82cc-1fdf888a7269.png'
                      : 'https://imagesize.hrwork.com/sp/files/764eb966-d76a-4aba-a60b-aa32bba4d204.png'
                  }
                />
              </View>
            </If>
          </View>
          <View className="resume-review">
            <View className="resume-top">
              <Image
                className="mymessageright"
                src={scaleImageSrc(
                  personDetail.userAvator ||
                    personDetail.avatarUrl ||
                    avater(personDetail.gender, personDetail.userId)
                )}
                mode="aspectFill"
                lazy-load
              />
              <View className="resume-top-right">
                <Text className="user-name">{personDetail.userName || personDetail.name}</Text>
                <View className="usrinfo-view">
                  <Text className="age">{userInfo.age}</Text>
                  <Text>{personDetail.gender === 'female' ? '女' : '男'}</Text>
                </View>
              </View>
            </View>
            <View className="self-recommend">
              <View className="self-recommend-top">
                <View className="top-top" />
                <View className="top-bottom" />
                <View className="top-right" />
              </View>
              <View className="self-recommend-bottom">
                <Text className="self-recommend-label">
                  自我评价：
                  <Text className="self-recommend-content">
                    {userInfo.intro || '这家伙很懒,什么都没写'}
                  </Text>
                </Text>
              </View>
            </View>
            <If visible={wantWork.length}>
              <View className="job-intention">
                <View className="job-intention-title">
                  <Text className="title-name">求职意向</Text>
                  <Text className="title-state">{userInfo.jobStatus}</Text>
                </View>
                <View className="job-intention-item">
                  {wantWork.map((item, index) => {
                    let comprehensive = JSON.parse(item.comprehensive)
                    let workNature = comprehensive.workNature[0]
                    let workPlace = comprehensive.workPlace || []
                    let wantWorkId = item.id
                    let jobPlace = item.jobPlace
                    return (
                      <IntentionCard
                        workNature={workNature}
                        workPlace={workPlace}
                        comprehensive={comprehensive}
                        wantWorkId={wantWorkId}
                        index={index}
                        jobPlace={jobPlace}
                        onTap={this.jumpTo}
                      />
                    )
                  })}
                </View>
              </View>
            </If>
            <If visible={educationInformation.length}>
              <View className="education-info">
                <Text className="education-info-title">教育信息</Text>
                {educationInformation.map(e => (
                  <View key={e.id} className="education-item-view">
                    <EducationCard dataSource={e} />
                  </View>
                ))}
              </View>
            </If>
            <If visible={workExp.length}>
              <View className="job-experience">
                <Text className="experience-title">工作经验</Text>
                <View className="experience-content">
                  {workExp.map(e => (
                    <View key={e.id} className="experience-item-view">
                      <WorkExpCard dataSource={e} />
                    </View>
                  ))}
                </View>
              </View>
            </If>
            <If visible={elegantDemeanour.length}>
              <View className="photo-alum">
                <Text className="photo-alum-title">我的相册</Text>
              </View>
            </If>
          </View>
          <If visible={elegantDemeanour.length}>
            <ScrollView className="photo-alum-img-view" scrollX>
              {elegantDemeanour.map((e, i) => (
                <Image
                  key={e.pic}
                  mode="aspectFill"
                  className={`photo-alum-img ${i === 0 ? 'photo-alum-img-first' : ''} ${
                    i === elegantDemeanour.length - 1 ? 'photo-alum-img-last' : ''
                  }`}
                  src={scaleImageSrc(e.pic, 460)}
                  data-url={e.pic}
                  onClick={this.openPic}
                />
              ))}
            </ScrollView>
          </If>
        </View>
        {/* 立即沟通按钮 */}
        <View className="chat-now-btn">
          <If visible={btnLoading}>
            <AtActivityIndicator mode="center" color="#c9c9c9" />
          </If>
          <If visible={!btnLoading}>
            <Form onSubmit={this.formSubmit} reportSubmit className="chat-btn-content">
              <Button formType="submit" className="chat-btn-content form-btn" onClick={this.callTo}>
                <Image src="https://imagesize.hrwork.com/sp/files/dda0d75d-2bab-4bb8-9ebe-76cc5d0ca74b.png" />
                <Text>立即沟通</Text>
              </Button>
            </Form>
          </If>
        </View>

        {/* 点击立即沟通 */}
        <AtActionSheet isOpened={modalReadyVisible}>
          <Dialog
            desc={`非会员拥有3次免费沟通机会，你已经沟通过${3 - Math.max(talkTime, 0)}次${
              talkTime > 0 ? `，还有${talkTime}次免费沟通机会` : ''
            }`}
            leftText="沟通"
            rightText="升级会员"
            onLeftOk={this.onConnect}
            onOk={this.gotoVipRecharge}
            onCancel={this.onCancel}
          />
        </AtActionSheet>

        {/* 点击拨打 */}
        <AtActionSheet isOpened={modalVisible}>
          <Dialog
            desc="您当前为企业非会员用户，3次免费沟通已用完。成为会员用户，拥有超多会员权限哦～"
            leftText="取消"
            rightText="升级会员"
            onLeftOk={this.onCancel}
            onOk={this.gotoVipRecharge}
          />
        </AtActionSheet>
      </View>
    )
  }
}

export default PersonDetail
